package hn.cch.apache;

import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.Watcher.Event;
import org.apache.zookeeper.ZooDefs;
import org.apache.zookeeper.ZooKeeper;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.CountDownLatch;

public class ZookeeperTest {

    private static final Logger logger = LoggerFactory.getLogger(ZookeeperTest.class);

    @Test
    public void testConnect() {
        CountDownLatch countDownLatch = new CountDownLatch(1);
        String url = "127.0.0.1:2181";
        try {
            ZooKeeper zooKeeper = new ZooKeeper(url, 30, watchedEvent -> {
                if (Event.KeeperState.SyncConnected == watchedEvent.getState()) {
                    if (Event.EventType.None == watchedEvent.getType()) {
                        logger.info("zookeeper connect success");
                        countDownLatch.countDown();
                    }

                }
            });
            countDownLatch.await();
            // 创建节点
            createNode(zooKeeper);
        } catch (IOException | InterruptedException e) {
            throw new RuntimeException(e);
        }
    }


    public void createNode(ZooKeeper zooKeeper) {

        try {

            String path = "/root/path/node";
            String data = "data";
            String result = null;
            String temp = "";
            // 注意节点需要逐级创建，不能一次创建多层节点
            String sep = "/";
            int index = 0;
            String node = "";
            while ((index = path.indexOf(sep, index)) > 0) {
                node = path.substring(0, index);
                logger.debug(node);
                if (zooKeeper.exists(node, false) == null) {
                    if (path.length() <= node.length() + 1) {
                        temp = data;
                    }
                    result = zooKeeper.create(node, temp.getBytes(StandardCharsets.UTF_8),
                        ZooDefs.Ids.OPEN_ACL_UNSAFE,
                        CreateMode.PERSISTENT);
                    logger.info("zookeeper create {}", result);
                }
            }
        } catch (KeeperException | InterruptedException e) {
            throw new RuntimeException(e);
        }
    }
}
